package com.edu.schoolforum.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.edu.schoolforum.enums.ResultEnum;
import com.edu.schoolforum.pojo.ImgUrl;
import com.edu.schoolforum.utils.CommonResult;
import com.edu.schoolforum.utils.ImgCommonResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author tao
 * @date 2021/8/6 21:37
 */
@Controller
@RestController
@RequestMapping("/api")
public class ImgController {
    /**
     * 图片上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public ImgCommonResult upload(MultipartFile file)throws IOException {
        String orginalFilename=file.getOriginalFilename();//获取文件的名称
        String flag= IdUtil.fastSimpleUUID();  //生成一个随机标识
        String rootFilePath=System.getProperty("user.dir")+"/src/main/resources/files/"+flag+"_"+orginalFilename;
        FileUtil.writeBytes(file.getBytes(),rootFilePath);
        ImgUrl i=new ImgUrl();
        i.setUrl("http://116.62.247.153:8081/api/"+flag);
        return ImgCommonResult.success(i);//
    }

    /**
     * 下载接口
     * @param flag
     * @param response
     * @return
     */
    @GetMapping("/{flag}")
    public void getFiles(@PathVariable String flag, HttpServletResponse response) {
        OutputStream os;  // 新建一个输出流对象
        String basePath = System.getProperty("user.dir") + "/src/main/resources/files/";  // 定于文件上传的根路径
        List<String> fileNames = FileUtil.listFileNames(basePath);  // 获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");  // 找到跟参数一致的文件
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName);  // 通过文件的路径读取文件字节流
                os = response.getOutputStream();   // 通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }
}
